// common/components/formItem/formItem.js
import ActionSheet, {
  ActionSheetTheme
} from 'tdesign-miniprogram/action-sheet/index';
import {
  uploadApi
} from '../../apis/system';
const dayjs = require('dayjs')
const {
  ITEM_TYPE
} = require('../../../config/formItem.config')

const computedBehavior = require('miniprogram-computed').behavior
const mixin_formItemType = require('../../mixins/formItemType')
const app = getApp()

Component({
  behaviors: [mixin_formItemType, computedBehavior],
  options: {
    multipleSlots: true
  },
  /**
   * 组件的属性列表
   */
  properties: {
    value: {
      type: null,
      value: ''
    },
    placeholder: {
      type: String,
      value: '请输入内容'
    },
    label: {
      type: String,
      value: '标题'
    },

    // 是否必填
    required: {
      type: Boolean,
      value: false
    },
    // 类型,用于控制展示不同的选项
    itemType: {
      type: String,
      value: ITEM_TYPE.DATE_TIME
    },
    // dickey值 在itemType为dicSelect 类型下生效
    dicKey: {
      type: String,
      value: ''
    },
    // dateFormatter 在datetime 类型下生效 值为 YYYY-MM-DD
    dateFormatter: {
      type: String,
      value: 'YYYY-MM-DD HH:mm'
    },
    // 是否显示下边框
    bordered: {
      type: Boolean,
      value: true,
    },
    // actionSheet 面板数据
    actionSheetList: {
      type: Array,
      value: []
    },
    // 部门选择类型  selectDept | selectDeptTeamUser | selectTeamUser
    choseType: {
      type: String,
      value: 'selectDept'
    },
    // 是否多选
    multiple: {
      type: Boolean,
      value: false
    },
    // 默认回显数据
    isInitDefaultValue: Boolean,
  },
  observers: {
    // dateFormatter: function (val) {
    //   let mode = ''
    //   if (val === 'YYYY-MM-DD') {
    //     mode = 'date'
    //   } else if (val === 'YYYY-MM') {
    //     mode = 'month'
    //   } else if (val === 'HH:mm:ss' || val === 'YYYY-MM-DD HH:mm:ss') {
    //     mode = 'second'
    //   } else if (val === 'HH:mm') {
    //     mode = 'minute'
    //   }
    //   this.setData({
    //     dataMode: mode
    //   })
    // }
  },

  lifetimes: {

    attached() {

      const {
        itemType,
        dateFormatter,
        value
      } = this.data
      let mode = ''
      if (dateFormatter === 'YYYY-MM-DD') {
        mode = 'date'
      } else if (dateFormatter === 'YYYY-MM') {
        mode = 'month'
      } else if (dateFormatter === 'HH:mm:ss' || dateFormatter === 'YYYY-MM-DD HH:mm:ss') {
        mode = 'second'
      } else if (dateFormatter === 'HH:mm' || dateFormatter === 'YYYY-MM-DD HH:mm') {
        mode = 'minute'
      }
      this.setData({
        dataMode: mode
      })


      const types = [
        ITEM_TYPE.TEXTAREA,
        ITEM_TYPE.RECORDING,
        ITEM_TYPE.UPLOAD,
        ITEM_TYPE.UPLOAD_IMAGE,
        ITEM_TYPE.CUSTOM,
        ITEM_TYPE.TEXT_INFO,
        ITEM_TYPE.DIC_TAG_SELECT,
        ITEM_TYPE.INPUT
      ]


      if ([ITEM_TYPE.DATE_TIME].includes(itemType)) {
        this.setData({
          value: value ? dayjs(value).format(dateFormatter) : ''
        })
      } else if (types.includes(itemType)) {
        this.setData({
          arrow: false
        })
      } else if ([ITEM_TYPE.ACTION_SHEET].includes(itemType)) {
        const len = this.data.actionSheetList.length
        this.setData({
          arrow: Boolean(len)
        })
      }
    },
    ready() {
      const self = this
      self.initDefaultValue()

    },
  },
  /**
   * 组件的初始数据
   */
  data: {
    arrow: true,
    valueLabel: '',
    datetimeVisible: false,
    currentPagePath: '',
    dicSelectPopupVisible: false,
    deptSelectPopupVisible: false,
    userSelectPopupVisible: false,
    fileList: [],
    imageList: [],
    dataMode: '',
    // 取消value值监听
    cancelValueWatch: false,
    dateDefaultValue: dayjs().format('YYYY-MM-DD HH:MM')
  },
  watch: {
    'value': function (val) {
      if (!this.data.cancelValueWatch) {
        this.initRenderValueLabel(val)

      }
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    // 初始化渲染 value对应的name
    initRenderValueLabel(value) {
      if (value) {
        const {
          itemType,
        } = this.data
        if (itemType === ITEM_TYPE.DEP_SELECT_POPUP) {
          const deptList = app.globalData.deptList
          const findValue = deptList.find(item => item.deptId == value)
          this.setData({
            valueLabel: findValue?.deptName || '',
          })
        }
      }
    },
    // 初始化默认数据的展示
    initDefaultValue() {
      const {
        itemType,
        dicKey,
        isInitDefaultValue
      } = this.data
      if (isInitDefaultValue && itemType === ITEM_TYPE.DIC_SELECT) {
        const {
          dicList
        } = getApp().globalData
        const value = dicList.find(item => item.type === dicKey).data
        console.log(value);
        this.setData({
          value: value[0].dictValue,
          valueLabel: value[0].dictLabel
        })
      }
    },



    onCellClick() {
      const self = this
      const {
        itemType,
        dateFormatter,
        value,
        currentPagePath,
        dicKey
      } = this.data

      if (ITEM_TYPE.DATE_TIME === itemType) {
        this.setData({
          datetimeVisible: true
        })
      } else if (ITEM_TYPE.DIC_SELECT === itemType) {
        // wx.$jump.navigateTo(SUB_PAGES.Filter.FILTER_DIC_SELECT.router)
        this.setData({
          dicSelectPopupVisible: true
        })
      } else if (ITEM_TYPE.DEP_SELECT_POPUP === itemType) {
        this.setData({
          deptSelectPopupVisible: true
        })
      } else if (ITEM_TYPE.USER_SELECT_POPUP === itemType) {
        this.setData({
          userSelectPopupVisible: true
        })
      } else if (ITEM_TYPE.CUSTOIM_SELECT === itemType) {
        this.triggerEvent('clickItem')
      } else if (ITEM_TYPE.ACTION_SHEET === itemType) {
        const len = self.data.actionSheetList.length
        if (len) {
          ActionSheet.show({
            theme: ActionSheetTheme.List,
            selector: '#t-action-sheet',
            context: this,
            items: self.data.actionSheetList,
          });
        }

      }

    },
    // 监听actionSheet
    onSelectedActionSheet(event) {

      this.triggerEvent('selectedActionSheet', event.detail.selected)
      this.setData({
        valueLabel: event.detail.selected.label
      })
    },
    //移除某个图片
    onRemoveImage(e) {
      const {
        index
      } = e.detail;
      const {
        imageList
      } = this.data;
      imageList.splice(index, 1);
      this.setData({
        imageList,
        value: imageList
      });
    },
    // 监听附件-拍照
    onPhoto(e) {
      let {
        imageList
      } = this.data
      imageList = [...imageList, ...e.detail.value]
      this.setData({
        imageList,
      })
      this.triggerEvent('photo', {
        value: imageList,
        type: 'camera'
      })
    },
    // 监听附件上传
    onFileUpload({
      detail
    }) {
      this.setData({
        // value: detail.value,
        fileList: detail.value
      })
      this.triggerEvent('onUploadData', {
        value: detail.value,
        type: 'file'
      })
    },


    // 监听附件列表
    onDelFileList({
      detail
    }) {
      this.triggerEvent('onUploadData', {
        value: detail.value,
        type: 'fileList'
      })
    },
    // 监听录音完成
    onRcording({
      detail
    }) {
      this.setData({
        value: detail.value
      })
      this.triggerEvent('changeRecording', {
        value: detail.value

      })
    },
    // 监听科室选择弹窗确认
    onConfirmDepSelectPopup({
      detail
    }) {
      this.setData({
        cancelValueWatch: true,
        value: detail.value,
        valueLabel: detail.valueLabel,

      })
      this.triggerEvent('selectDept', {
        value: detail.other
      })
    },
    // 监听字典选择弹窗
    onConfirmDicSelectPopup({
      detail
    }) {

      this.setData({
        cancelValueWatch: true,
        value: detail.value,
        valueLabel: detail.valueLabel
      })
    },

    // 监听时间确认
    onConfirmDateTimePicker(e) {
      this.setData({
        value: e.detail.value
      })
      this.triggerEvent('changeTime', {
        value: e.detail.value
      })
    },
    // 取消按钮点击时触发
    onHideDateTimePicker(e) {
      console.log(e, 'onHideDateTimePicker');

    },
    // 监听textarea 的输入
    onChangeTextArea({
      detail
    }) {
      this.setData({
        value: detail.value
      })
      this.triggerEvent('changeTextArea', {
        value: detail.value
      })
    },
    // 监听input输入
    onInput({
      detail
    }) {

      this.setData({
        value: detail.value
      })
      this.triggerEvent('changeInput', {
        value: detail.value
      })
    },
    onUserSelectCancel() {
      this.setData({
        userSelectPopupVisible: false
      })
    },
    onUserSelectConfirm(e) {
      this.setData({
        userSelectPopupVisible: false
      })
    },
    onTag(e) {
      this.setData({
        value: e.detail.value
      })
      this.triggerEvent('changeTag', {
        value: e.detail.value
      })
    }
  }
})